import fs from "fs";
import { resolve } from "path";
import { wrapperEnv } from "./webPatch/vite/getEnv";
import { createVitePlugins } from "./webPatch/vite/plugins";
import { defineConfig, loadEnv } from "vite";

const webResource = filePath => {
  return resolve(__dirname, `./web/${filePath}`);
};
// 版本号
const getAppVersion = () => {
  let today = new Date();
  const padZero = inValue => {
    return (inValue + "").padStart(2, "0");
  };
  let ret =
    today.getFullYear() +
    "-" +
    padZero(today.getMonth() + 1) +
    "-" +
    padZero(today.getDate()) +
    " " +
    padZero(today.getHours()) +
    ":" +
    padZero(today.getMinutes()) +
    ":" +
    padZero(today.getSeconds());
  return ret;
};

const outDir = process.cwd() + "/build/generic-legacy/web";

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // const root = process.cwd();
  const root = process.cwd() + "/webPatch";

  // 清空 rmDir 中指定目录下的文件
  let rmDir = [outDir + "/assets/js", outDir + "/assets/css"];
  for (let item of rmDir) {
    fs.rm(item, { recursive: true, force: true }, err => {
      if (err) {
        console.error(`Failed to clean ${item}:`, err);
      } else {
        console.log(`Cleaned ${item}`);
      }
    });
  }
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);

  return {
    base: viteEnv.VITE_PUBLIC_PATH,
    root,
    resolve: {
      // alias: {
      //   /** mapping 用于vue */
      //   "@": resolve(__dirname, "./webPatch"),
      // },
      alias: {
        /** 以下mapping，用于 pdf.js */
        pdfjs: resolve(__dirname, "./src"),
        "pdfjs-lib": resolve(__dirname, "./src/pdf.js"),
        "pdfjs-web": resolve(__dirname, "./web"),
        "fluent-bundle": resolve(
          __dirname,
          "./node_modules/@fluent/bundle/esm/index.js"
        ),
        "fluent-dom": resolve(
          __dirname,
          "./node_modules/@fluent/dom/esm/index.js"
        ),
        "cached-iterable": resolve(
          __dirname,
          "./node_modules/cached-iterable/src/index.mjs"
        ),
        "display-fetch_stream": resolve(
          __dirname,
          "./src/display/fetch_stream.js"
        ),
        "display-network": resolve(__dirname, "./src/display/network.js"),
        "display-node_stream": resolve(__dirname, "./src/display/stubs.js"),
        "display-node_utils": resolve(__dirname, "./src/display/stubs.js"),
        "web-alt_text_manager": webResource("./alt_text_manager.js"),
        "web-annotation_editor_params": webResource(
          "./annotation_editor_params.js"
        ),
        "web-download_manager": webResource("./download_manager.js"),
        "web-external_services": webResource("./genericcom.js"),
        "web-null_l10n": webResource("./genericl10n.js"),
        "web-pdf_attachment_viewer": webResource("./pdf_attachment_viewer.js"),
        "web-pdf_cursor_tools": webResource("./pdf_cursor_tools.js"),
        "web-pdf_document_properties": webResource(
          "./pdf_document_properties.js"
        ),
        "web-pdf_find_bar": webResource("./pdf_find_bar.js"),
        "web-pdf_layer_viewer": webResource("./pdf_layer_viewer.js"),
        "web-pdf_outline_viewer": webResource("./pdf_outline_viewer.js"),
        "web-pdf_presentation_mode": webResource("./pdf_presentation_mode.js"),
        "web-pdf_sidebar": webResource("./pdf_sidebar.js"),
        "web-pdf_thumbnail_viewer": webResource("./pdf_thumbnail_viewer.js"),
        "web-preferences": webResource("./genericcom.js"),
        "web-print_service": webResource("./pdf_print_service.js"),
        "web-secondary_toolbar": webResource("./secondary_toolbar.js"),
        "web-toolbar": webResource("./toolbar.js"),

        /** 以下mapping，用于vue */
        "@": resolve(__dirname, "./webPatch"),
      },
    },
    define: {
      appVersion: JSON.stringify(getAppVersion()),
    },
    plugins: createVitePlugins(viteEnv),
    esbuild: {
      // 去掉 console，debugger
      // pure: ["console.log", "debugger"],
    },
    build: {
      manifest: true, // 启用 manifest 文件生成
      outDir,
      minify: "esbuild",
      assetsInlineLimit: 100240, // 将小于 100KB 的文件转换为 base64

      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          // Static resource classification and packaging
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks(id) {
            if (
              id.includes("/src/utils/http.ts") ||
              id.includes("/src/utils/index.ts")
            ) {
              // 将 'http.ts' 和 'index.ts' 强制打包到同一个 chunk 中
              return "utils";
            }
          },
        },
      },
    },
  };
});
